<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="nonConformanceType === 'material' ? 12 : 24">
            <a-form-model-item label="处理单号" :labelCol="nonConformanceType === 'material' ? labelCol2 : labelCol" :wrapperCol="nonConformanceType === 'material' ? wrapperCol2 : wrapperCol"
                               prop="nonConformanceNumber">
              <a-input v-model="model.nonConformanceNumber" placeholder="保存自动生成" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="nonConformanceType === 'material'">
            <a-form-model-item label="审批流程" :labelCol="nonConformanceType === 'material' ? labelCol2 : labelCol" :wrapperCol="nonConformanceType === 'material' ? wrapperCol2 : wrapperCol">
              <j-dict-select-tag
                type="list"
                v-model="model.approveFlow"
                dictCode="non_conformance_flow"
                placeholder="请选择审批流程"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="不合格现象" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="nonConformancePhenomenon">
              <a-textarea v-model="model.nonConformancePhenomenon" :rows="4" placeholder="请输入不合格现象" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="处理意见" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="processingOpinion">
              <j-dict-select-tag
                @change="handleProcessingOpinionChange"
                type="radio"
                v-model="model.processingOpinion"
                :dictCode="processingOpinionDictCode" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="model.processingOpinion==='1'">
            <a-form-model-item label="保质期" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="shelfLife2">
              <a-input-number
                @change="calculateExpirationDate"
                v-model="model.shelfLife2"
                placeholder="请输入保质期（天）"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!-- 限用日期 -->
          <a-col :span="12" v-if="model.processingOpinion==='1'">
            <a-form-model-item label="限用日期" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="limitUseDate">
              <a-date-picker v-model="model.expirationDate2" valueFormat="YYYY-MM-DD" disabled style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="nonConformanceType === 'material' && model.processingOpinion==='1'">
            <a-form-model-item label="扣款金额" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="deductionAmount">
              <a-input-number v-model="model.deductionAmount" placeholder="请输入扣款金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, postAction } from '@/api/manage'
import dayjs from 'dayjs'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'

export default {
  name: 'NonConformanceForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    nonConformanceType: {
      type: String,
      default: 'material',
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false
    }
  },
  data() {
    return {
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        approveFlow: [{ required: true, message: '审批流程不能为空!' }],
      },
      url: {
        edit: '/qms/non-conformance/edit',
        queryById: '/qms/non-conformance/queryById'
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    processingOpinionDictCode() {
      if (this.nonConformanceType === 'finished-product') {
        return 'qc_finished_product_processing_opinion'
      } else if (this.nonConformanceType === 'material') {
        return 'qc_material_processing_opinion'
      }
      return ''
    }
  },
  created() {
    // 审批进来显示业务数据
    if (this.customFormData.id != null) {
      this.model = this.customFormData
    }
  },
  methods: {
    edit(record) {
      this.model = Object.assign({}, record)
      if(!this.formDisabled){
        this.model.processingOpinion = '1'
      }
      this.handleProcessingOpinionChange(this.model.processingOpinion)
      this.visible = true
    },
    async handleSubmit() {
      const validate = await this.$refs.form.validate()
      if (!validate) {
        return
      }
      const formData = {
        id: this.model.id,
        nonConformancePhenomenon: this.model.nonConformancePhenomenon,
        processingOpinion: this.model.processingOpinion,
        shelfLife2: this.model.shelfLife2,
        approveFlow: this.model.approveFlow,
        deductionAmount: this.model.deductionAmount
      }
      this.request(formData)
    },
    request(formData) {
      this.confirmLoading = true
      postAction(this.url.edit, formData)
        .then((res) => {
          if (res.success) {
            if (this.nonConformanceType === 'material') {
              this.model.dataId = this.model.id
              this.applySubmit(this.model)
            }
            this.$message.success('保存成功')
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    handleProcessingOpinionChange(value) {
      if (value === '1') {
        this.setDefaultShelfLifeAndExpirationDate()
      } else {
        this.model.shelfLife2 = null
      }
    },
    setDefaultShelfLifeAndExpirationDate() {
      this.model.shelfLife2 = this.model.shelfLife2 || this.model.shelfLife
      this.calculateExpirationDate()
    },
    calculateExpirationDate() {
      this.model.expirationDate2 = null
      if (!this.model.productionDate || !this.model.shelfLife2) {
        return
      }
      const today = dayjs(this.model.productionDate)
      const expirationDate = today.add(parseInt(this.model.shelfLife2), 'day')
      this.model.expirationDate2 = expirationDate.format('YYYY-MM-DD')
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }
      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
        } else {
          const params = Object.assign({ dataId: record.dataId }, record)
          definitionStartByDataId(record.dataId, 'nonConformanceService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.error(res.message)
              }
              this.$emit('ok')
            })
        }
      })
    }
  }
}
</script>